import json

from django.conf import settings
from django.core.paginator import EmptyPage, Paginator
from django.http import JsonResponse
from django.views import View

from aijia_rental.utils.views import LoginRequiredJSONMixin
from lina.models import Area, Facility, House, HouseImage, HouseFacility

from lishiliang.models import User
from lvhanxun.models import Order


# 城区列表
class CityProperListView(View):

    def get(self, request):
        """获取数据库中的数据，
        并返回指定格式"""

        try:
            areas = Area.objects.all().order_by('id')
        except Exception:
            return JsonResponse({'errmsg': '数据查询错误',
                                 'errno': "4001"})

        data = [{
            "aid": area.id,
            "aname": area.name
        } for area in areas]

        # data.append()

        return JsonResponse({'errmsg': 'ok',
                             'errno': "0",
                             'data': data})


# 我的房屋列表
class HouseListView(LoginRequiredJSONMixin, View):

    # 我的房屋列表
    # 我的房屋列表
    def get(self, request):

        # 获取当前用户所有的房屋数据
        try:
            houses_object = House.objects.filter(user=request.user)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '查询该用户房屋数据失败'})

        list = []
        # 遍历房屋数据
        for house in houses_object:
            dict = {
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url": settings.QNY_URL + str(house.index_image_url),
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": settings.QNY_URL + str(house.user.avatar)
            }
            list.append(dict)

        data = {"houses": list}

        return JsonResponse({"errno": "0",
                             "errmsg": "ok",
                             "data": data})


# 发布房源
class ReleaseHouseView(View):

    # 发布房源
    def post(self, request):

        user_id = request.user.id
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')

        if not all([title, price, area_id, address,
                    room_count, acreage, unit, capacity,
                    beds, deposit, deposit, min_days, max_days, facility]):
            return JsonResponse({'errno': "4103",
                                 'errmsg': '缺少参数'})

        # 将数据转化成整型
        try:
            price = int(price)
            room_count = int(room_count)
            acreage = int(acreage)
            capacity = int(capacity)
            min_days = int(min_days)
            max_days = int(max_days)
            deposit = int(deposit)

        except Exception:
            return JsonResponse({'errno': "4004",
                                 'errmsg': '数据错误'})

        # 判断地区是否存在
        try:
            area = Area.objects.get(id=area_id)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '地址不存在'})

        # 判断和获取用户的数据
        try:
            user = User.objects.get(id=user_id)
        except Exception:
            return JsonResponse({'errno': "4104",
                                 'errmsg': '用户不存在或未激活'})

        # 判断设施是否存在
        try:
            facilitys = Facility.objects.filter(id__in=facility)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '数据库查询错误'})

        try:

            for index in facility:
                # 在 House中添加数据
                house = House.objects.create(
                    user=user,
                    area=area,
                    title=title,
                    price=price,
                    address=address,
                    room_count=room_count,
                    acreage=acreage,
                    unit=unit,
                    capacity=capacity,
                    beds=beds,
                    deposit=deposit,
                    min_days=min_days,
                    max_days=max_days,

                )
                house.facility.add(index)
                house.save()
        except Exception:
            return JsonResponse({'errno': "4500",
                                 'errmsg': '数据存储错误'})

        data = {'house_id': house.id}

        return JsonResponse({"errno": "0",
                             "errmsg": "发布成功",
                             "data": data})
    #  刘燕伟  接口  搜索
    def get(self, request):

        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk', 'order_count')
        p = request.GET.get('p')

        try:
            if aid:
                house_data = House.objects.filter(area_id=aid,)

            else:
                house_data = House.objects.all()



        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        try:

            paginator = Paginator(house_data, 1)
            page_skus = paginator.page(p)

        except EmptyPage:
            return JsonResponse({'erron': '4001',
                                 'errmsg': 'page页码出错'})

        house_list = []
        data = {
            'houses': house_list,

        }

        for obj_house in page_skus:

            order_count = obj_house.order_count
            house_id = obj_house.id
            title = obj_house.title
            create_time = obj_house.create_time
            price = obj_house.price
            area_name = obj_house.area.name
            address = obj_house.address
            room_count = obj_house.room_count
            img_urls = obj_house.index_image_url
            user_avater = str(obj_house.user.avatar)


            url = settings.QNY_URL
            result = url + img_urls
            user_avater = url + user_avater

            house_list.append({"address": address,
                               "area_name": area_name,
                               "ctime": create_time,
                               "house_id": house_id,
                               "img_url": result,
                               "order_count": order_count,
                               "price": price,
                               "room_count": room_count,
                               "title": title,
                               "user_avatar": user_avater})
            # try:
            #     num =Order.objects.filter(house_id=house_id)
            # except Exception as e:
            #     pass
            try:
                totoal_pages = paginator.num_pages

            except EmptyPage:
                return JsonResponse({'erron': '4001',
                                     'errmsg': 'page页码出错'})
            data['total_page'] = totoal_pages
        # if num:
        return JsonResponse({
                            'data': data,
                            'errmsg': "请求成功",
                            'errno': "0"})

# 房屋详情
class HouserDetailsView(View):

    def get(self, request, house_id):
        """首页房屋推荐"""

        # 首先获取房子的信息
        try:
            house = House.objects.get(id=house_id)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '房屋信息查询错误'})

        # 获取订单信息
        try:
            orders = Order.objects.filter(house=house)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '订单信息查询错误'})

        # 获取房屋图片地址
        try:
            house_images = HouseImage.objects.filter(house=house)
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '房屋图片查询错误'})

        # 判断用户是否登录
        if request.user.is_authenticated:
            # 获取用户id
            user_id = request.user.id
        else:
            user_id = -1

        # 评论列表
        # 存储的内容  ==> comment 评论信息  ctime
        # user_name 评论用户名字
        comments = []
        for order in orders:
            comments.append({
                "comment": order.comment,
                "ctime": order.create_time,
                "user_name": order.user.username
            })

        # 设施列表
        facilities = [house_fac.id for house_fac in house.facility.all()]

        # url = settings.QNY_URL
        # image_path = url + house.index_image_url
        # 房屋图片列表
        img_urls = []

        for image in house_images:
            img_urls.append(settings.QNY_URL + str(image.url))
        try:
            house_dict = {
                # 根据获取的数据进行格式处理
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": facilities,
                "hid": house.id,
                "img_urls": img_urls,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": settings.QNY_URL + str(house.user.avatar),
                "user_id": int(house.user.id),
                "user_name": house.user.username,
            }
        except Exception:
            return JsonResponse({'errno': "4004",
                                 'errmsg': '数据处理失败'})

        data_dict = {
            "house": house_dict,
            "user_id": user_id
        }

        return JsonResponse({"errmsg": "OK",
                             "errno": "0",
                             "data": data_dict
                             })


# 房屋首页
class HouseIndexView(View):

    def get(self, request):
        """首页房源推荐"""

        try:
            #  获取所有房屋信息
            houses = House.objects.order_by("-order_count")[:5]
        except Exception:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '房屋信息查询错误'})

        data = []
        for house in houses:
            data.append({
                "house_id": house.id,
                "img_url": settings.QNY_URL + str(house.index_image_url),
                "title": house.title
            })

        return JsonResponse({"errmsg": "OK",
                             "errno": "0",
                             "data": data})


